<script setup lang="ts">
  import { ref, watch, nextTick, onUnmounted } from "vue";
  import { useRoute } from "vue-router";
  import { EMClient } from "@/easemob/index";
  import {
    EASEMOB_TEST_NORMAL_CHATROOM_ID,
    EASEMOB_TEST_LOGIN_USER,
    EASEMOB_TEST_LOGIN_PWD,
  } from "@/easemob/constants";
  import type {
    MessagesType,
    MessageBody,
    CreateTextMsgParameters,
  } from "easemob-websdk/types/message";
  /* 登录环信逻辑 */
  const route = useRoute();
  //登录环信
  const loginEaseIM = async () => {
    try {
      if (route.query.userId && route.query.userPwd) {
        await EMClient.open({
          username: route.query.userId as string,
          password: route.query.userPwd as string,
        });
      } else {
        await EMClient.open({
          username: EASEMOB_TEST_LOGIN_USER,
          password: EASEMOB_TEST_LOGIN_PWD,
        });
      }
      // 登录成功后执行加入聊天室
      await joinChatRoom();
    } catch (error) {
      console.log("登录失败");
    }
  };
  loginEaseIM();

  /* 聊天室操作逻辑 */
  //互动聊天室
  const joinNormalChatRoom = () => {
    return EMClient.chatroom.joinChatRoom({
      roomId: EASEMOB_TEST_NORMAL_CHATROOM_ID,
      message: "普通聊天室",
      ext: "此处可填入用户加入聊天室的头像昵称等信息",
    });
  };
  //加入聊天室
  const joinChatRoom = async () => {
    try {
      await joinNormalChatRoom();
      console.log(">>>>>加入聊天室成功");
      await getChatRoomHistory();
    } catch (error) {
      console.log(">>>>>加入聊天室失败", error);
    }
  };

  /* 消息相关逻辑 */
  //获取聊天室历史消息
  const getChatRoomHistory = async () => {
    try {
      console.log(">>>>>获取聊天室历史消息");
      const { messages } = await EMClient.contact.getHistoryMessages({
        targetId: EASEMOB_TEST_NORMAL_CHATROOM_ID,
        chatType: "chatRoom",
        pageSize: 20,
        searchDirection: "up",
      });
      console.log(">>>>>获取聊天室历史消息成功", messages);
      if (messages?.length > 0) {
        chatRoomMessages.value = messages.reverse();
      }
    } catch (error) {
      console.log(">>>>>获取聊天室历史消息失败");
    }
  };
  //聊天室消息列表
  const chatRoomMessages = ref<MessagesType[]>([]);
  const messageListRef = ref<HTMLElement>();
  //【优化点】控制chatRoomMessages的最大长度为50条, 超出部分删除,防止danmuList过长, 导致页面卡顿。
  const maxMessageLength = 20;
  const deleteMessage = () => {
    if (chatRoomMessages.value.length > maxMessageLength) {
      console.log('>>>>>消息列表溢出执行删除')
      chatRoomMessages.value = chatRoomMessages.value.slice(
        chatRoomMessages.value.length - maxMessageLength
      );
    }
  };
  //更新消息列表
  const updateMessageList = (msg:MessagesType) => {
    //判断消息来源是否是当前所处聊天室再做消息列表更新。
    if(msg.to!== EASEMOB_TEST_NORMAL_CHATROOM_ID) return
    chatRoomMessages.value.push(msg);
    deleteMessage();
  };
  //挂载监听聊天室接收消息回调函数
  const mountMessageListener = () => {
    EMClient.addEventHandler("changeRoom", {
      onTextMessage: (msg) => {
        updateMessageList(msg)
      },
    });
  };
  mountMessageListener();

  //监听changeRoom消息变化使其列表滚动置底
  watch(
    chatRoomMessages,
    () => {
      nextTick(() => {
        if (messageListRef.value) {
          //使messageListRef滚动到可视区域
          messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
        }
      });
    },
    { deep: true }
  );
  //发送聊天室弹幕
  const inputContent = ref("");
  const sendMessage = async () => {
    const paramas: CreateTextMsgParameters = {
      to: EASEMOB_TEST_NORMAL_CHATROOM_ID,
      msg: inputContent.value || "测试消息",
      chatType: "chatRoom",
      type: "txt",
    };
    try {
      const msg = EMClient.Message.create(paramas);
      const { message } = await EMClient.send(msg as MessageBody);
      inputContent.value = "";
      updateMessageList(message)
    } catch (error) {
      console.log(">>>>>发送聊天室弹幕失败", error);
    }
  };
  /* 组件销毁 */
  //离开聊天室
  //关闭环信连接
  onUnmounted(async () => {
    await EMClient.chatroom.leaveChatRoom({
      roomId: EASEMOB_TEST_NORMAL_CHATROOM_ID,
    });
    EMClient.close();
  });
</script>

<template>
  <div class="chat-room-container">
    <h1>欢迎来到环信聊天室演示页面</h1>
    <p>这里是一个简单的聊天室应用，使用环信即时通讯服务。</p>
    <!-- 聊天室弹幕滚动区 -->
    <div class="chat-room-messages" ref="messageListRef">
      <div
        class="message-list-item"
        v-for="(message, index) in chatRoomMessages"
        :key="index"
      >
        <span class="sender"
          >{{ message.from === EMClient.user ? "我" : message.from }}：</span
        >
        <span class="content" v-if="message.type === 'txt'">{{ message.msg }}</span>
      </div>
    </div>
    <!-- 聊天室弹幕发送区 -->
    <div class="chat-room-input">
      <input v-model="inputContent" type="text" placeholder="输入消息" />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<style scoped>
  .chat-room-container {
    position: relative;
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
  }
  .chat-room-messages {
    position: absolute;
    left: 0;
    bottom: 120px;
    width: 60%;
    height: 150px;
    overflow: auto;
    /* background-color: rgba(52, 50, 50, 0.2); */
    border-radius: 10px;
  }
  /* 弹幕气泡样式 */

  .message-list-item {
    white-space: nowrap;
    padding: 8px 12px;
    background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
    color: #fff; /* 文字颜色 */
    border-radius: 20px; /* 圆角大小 */
    font-size: 14px; /* 字体大小 */
    margin: 5px 0;
  }
  .chat-room-input {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 80px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
  }
</style>

<route lang="json">
{
  "name": "live-chatroom",
  "meta": {
    "title": "📊 环信聊天室演示",
    "i18n": "menus.liveChatroom"
  }
}
</route>
